﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebHoiChoMuaBan.Controllers.Helpers;
using WebHoiChoMuaBan.Models;
using WebHoiChoMuaBan.Controllers.Utility;
using System.Drawing;
using System.IO;
using WebHoiChoMuaBan.Controllers.Global;

namespace WebHoiChoMuaBan.Controllers.Private
{
    public class ProductController : PrivateController
    {
        private void Init(int? uid)
        {
            ViewData["mid"] = "product";
            ViewData["child_menu"] = "posting";
            LoadTimeAndCurrency();
            //Load tất cả các danh mục
            CategoryHelper cateHelper = new CategoryHelper();
            // ViewData["Categories"] = new SelectList(cateHelper.GetListParentCategory(), "CateId", "CateName");
            ViewData["Categories"] = new SelectList(cateHelper.getMemberCategory(uid), "CateId", "CateName");
            UtilityModel uModel = new UtilityModel();
            ViewData["Provinces"] = uModel.ListProvince();
        }

        public ActionResult Index(int? uid)
        {
            if (uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null) //Load được Member
            {
                Init(uid);
                return View("~/Views/Private/ProductCreate.aspx");
            }
            return HomePage();
        }

        public ActionResult CreateProduct(int? uid)
        {
            if (uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null) //Load được Member
            {
                ViewData["mid"] = "product";
                ViewData["child_menu"] = "posting";
                LoadTimeAndCurrency();
                CategoryHelper cateHelper = new CategoryHelper();
                List<Category> cateLv2 = cateHelper.getMemberCategory(uid);
                //List<int?> childCat = new List<int?>();
                //foreach (Category cat in cateLv2)
                //{
                //    if (childCat.Count > 0)
                //    {
                //        if (!childCat.Contains(cat.ParentCateId))
                //            childCat.Add(cat.ParentCateId);
                //    }
                //    else
                //        childCat.Add(cat.ParentCateId);
                //}
                List<Category> selectedList = cateHelper.GetListParentCategory();
                ViewData["Categories"] = new SelectList(selectedList, "CateId", "CateName");
                UtilityModel uModel = new UtilityModel();
                ViewData["Provinces"] = uModel.ListProvince();
                return View("~/Views/Private/ProductCreate.aspx");
            }
            return HomePage();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult AddProduct(FormCollection data)
        {
            int? uid = null;
            if (Session["MemId"] != null)
                uid = (int)Session["MemId"];
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                Init(uid);
                string newsType = data.Get("NewsType");
                ViewData["NewsType"] = newsType;
                //ViewData["ddlCateLevel1"] = int.Parse(data.Get("ddlCateLevel1"));
                //Đăng phần sản phầm
                if (newsType.Equals("Product"))
                {
                    NewsProduct newsProduct = new NewsProduct();
                    newsProduct.NProNeedType = data.Get("grpDemand");
                    if(data.Get("ddlCateLevel2")!=null)
                    newsProduct.CateId = int.Parse(data.Get("ddlCateLevel2"));
                    else
                        newsProduct.CateId = int.Parse(data.Get("ddlCateLevel1"));
                    newsProduct.ProvId = int.Parse(data.Get("ddlProvince"));
                    newsProduct.NProTitle = data.Get("txtTitle");
                    newsProduct.NProFrom = data.Get("txtFrom");
                    decimal price = data.Get("txtPrice") == "" ? 0 : decimal.Parse(data.Get("txtPrice"));
                    newsProduct.NProPrice = price;
                    newsProduct.NProIntro = data.Get("txtIntro");
                    newsProduct.NProContent = data.Get("txtDetailContent");
                    newsProduct.NProState = true;//active
                    newsProduct.NProDate = DateTime.Now;
                    newsProduct.MemId = (int)Session["MemId"];
                    ViewData["NewsProduct"] = newsProduct;
                    if (newsProduct.IsValid)
                    {
                        //Thêm NewsProduct vào CSDL
                        NewsProductHelper newsProHelper = new NewsProductHelper();
                        newsProHelper.Add(newsProduct);
                        newsProHelper.Save();

                        //Sau khi insert Thông tin của sản phẩm vào CSDL thì mới lưu thông tin hình ảnh
                        //Mục đích là để tạo ra NProId trước, sau đó mới newsProductThumb mới tham chiếu vào id đó
                        //Phần hình minh họa
                        NewsProductThumbHelper newsProThumbHelper = new NewsProductThumbHelper();
                        NewsProductThumb newsProductThumb = null;
                        UploadController upload = new UploadController();
                        bool isMainThumb = true;
                        foreach (string file in Request.Files)
                        {
                            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                            ImageHelper imgHelper = new ImageHelper();
                            if (imgHelper.CheckInfoIcon(hpf))
                            {
                                string fileName = hpf.FileName;
                                newsProductThumb = new NewsProductThumb();
                                newsProductThumb.NProId = newsProduct.NProId;
                                newsProductThumb.NProThumbName = fileName;
                                string path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + hpf.FileName);
                                if (isMainThumb)
                                {
                                    //Up hình lên server
                                    imgHelper.uploadImage(path, hpf, 200, 200);
                                    //Thêm vào CSDL 
                                    newsProductThumb.NProThumbIsMain = true;
                                    isMainThumb = false;
                                    newsProThumbHelper.Add(newsProductThumb);
                                    newsProThumbHelper.Save();
                                    continue;
                                }
                                newsProductThumb.NProThumbIsMain = false;

                                //Upload hình lên server
                                imgHelper.uploadImage(path, hpf, 200, 200);
                                //Thêm vào CSDL
                                newsProThumbHelper.Add(newsProductThumb);
                                newsProThumbHelper.Save();
                            }
                        }
                    }
                    else
                    {
                        foreach (var issue in newsProduct.GetRuleViolations())
                        {
                            ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                        }
                        Init(uid);
                        return View("~/Views/Private/ProductCreate.aspx");
                    }
                }
                else //Đăng phần nhà đất
                {
                    NewsProduct newsProduct = new NewsProduct();
                    newsProduct.NProNeedType = data.Get("grpDemand");
                    if (data.Get("ddlCateLevel2") != null)
                        newsProduct.CateId = int.Parse(data.Get("ddlCateLevel2"));
                    else
                        newsProduct.CateId = int.Parse(data.Get("ddlCateLevel1"));
                    newsProduct.ProvId = int.Parse(data.Get("ddlProvince"));
                    newsProduct.NProTitle = data.Get("txtTitle");
                    decimal price = data.Get("txtPrice") == "" ? 0 : decimal.Parse(data.Get("txtPrice"));
                    newsProduct.NProPrice = price;
                    newsProduct.NProPriceUnit = data.Get("cbbCurrency");
                    newsProduct.NProIntro = data.Get("txtIntro");
                    newsProduct.NProContent = data.Get("txtDetailContent");
                    newsProduct.NProDate = DateTime.Now;
                    newsProduct.MemId = (int)Session["MemId"];
                    ViewData["NewsProduct"] = newsProduct;
                    if (newsProduct.IsValid)
                    {
                        //Thêm các thuộc tính của ngôi nhà vào CSDL trước, mục đích là tạo ra id trước
                        //sau đó mới tham chiếu id vừa tạo vào bảng NewsProduct
                        RealEstateAttribute attr = new RealEstateAttribute();

                        // Phần Tiện ích
                        attr.RAttrWaterSystem = data.Get("ckbWaterSystem") != null ? true : false;
                        attr.RAttrPrivateElecClock = data.Get("ckbPrivateElecClock") != null ? true : false;
                        attr.RAttrUsableArea = data.Get("txtUsableArea") != "" ? double.Parse(data.Get("txtUsableArea")) : 0;
                        attr.RAttrTotalArea = data.Get("txtTotalArea") != "" ? double.Parse(data.Get("txtTotalArea")) : 0;
                        attr.RAttrFloorCount = data.Get("txtFloorCount") != "" ? int.Parse(data.Get("txtFloorCount")) : 0;

                        //Phần Nội thất - Tiện nghi
                        attr.RAttrElevator = data.Get("ckbElevator") != null ? true : false;
                        attr.RAttrGarden = data.Get("cbkGarden") != null ? true : false;
                        attr.RAttrPhoneLine = data.Get("ckbPhoneLine") != null ? true : false;
                        attr.RAttrGarage = data.Get("ckbGarage") != null ? true : false;
                        attr.RAttrSecurity24 = data.Get("ckbSecurity24") != null ? true : false;
                        attr.RAttrAirCondition = data.Get("ckbAirCondition") != null ? true : false;
                        attr.RAttrSwimmingPool = data.Get("ckbSwimmingPool") != null ? true : false;
                        attr.RAttrLivingRoom = data.Get("ckbLivingRoom") != null ? true : false;
                        attr.RAttrCarParking = data.Get("ckbCarParking") != null ? true : false;
                        attr.RAttrTopFloor = data.Get("ckbTopFloor") != null ? true : false;
                        attr.RAttrKitchen = data.Get("ckbKitchen") != null ? true : false;

                        //Phần Văn hóa - Xã hội
                        attr.RAttrNearPark = data.Get("ckbNearPark") != null ? true : false;
                        attr.RAttrNearComCentral = data.Get("ckbNearComCentral") != null ? true : false;
                        attr.RAttrNearHighSchool = data.Get("ckbNearHighSchool") != null ? true : false;
                        attr.RAttrForBusiness = data.Get("ckbForBusiness") != null ? true : false;
                        attr.RAttrForEnterCenter = data.Get("ckbNearEnterCenter") != null ? true : false;
                        attr.RAttrNearColleage = data.Get("ckbNearColleage") != null ? true : false;
                        attr.RAttrNearMarket = data.Get("ckbNearMarket") != null ? true : false;
                        attr.RAttrNearPrimarySchool = data.Get("ckbNearPrimarySchool") != null ? true : false;
                        attr.RAttrNearKinderGarden = data.Get("ckbNearKinderGarden") != null ? true : false;
                        attr.RAttrNearHospital = data.Get("ckbNearHospital") != null ? true : false;
                        attr.RAttrNearSecondarySchool = data.Get("ckbNearSecondarySchool") != null ? true : false;
                        attr.RAttrHighIntelResident = data.Get("ckbHighIntelResident") != null ? true : false;
                        attr.RAttrRedBook = false;
                        attr.RAttrPinkBook = false;
                        attr.RAttrHandwrittingBook = false;
                        //Tình trạng - Pháp lý
                        switch (data.Get("Book"))
                        {
                            case "RedBook": attr.RAttrRedBook = true; break;
                            case "PinkBook": attr.RAttrPinkBook = true; break;
                            case "rbtHandWritingBook": attr.RAttrHandwrittingBook = true; break;
                        }

                        //Thêm attr vào CSDL
                        RealEStateAttributeHelper attrHelper = new RealEStateAttributeHelper();
                        attrHelper.Add(attr);
                        attrHelper.Save();

                        //Tham chiếu các thuộc tính nhà đất vào đối tượng "newsProduct"
                        newsProduct.RAttrId = attr.RAttrId;

                        //Thêm NewsProduct vào CSDL
                        NewsProductHelper newsProHelper = new NewsProductHelper();
                        newsProHelper.Add(newsProduct);
                        newsProHelper.Save();

                        //Sau khi insert Thông tin của sản phẩm vào CSDL thì mới lưu thông tin hình ảnh
                        //Mục đích là để tạo ra NProId trước, sau đó mới newsProductThumb mới tham chiếu vào id đó
                        //Phần hình minh họa
                        NewsProductThumbHelper newsProThumbHelper = new NewsProductThumbHelper();
                        NewsProductThumb newsProductThumb = null;

                        bool isMainThumb = true;
                        foreach (string file in Request.Files)
                        {
                            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                            ImageHelper imgHelper = new ImageHelper();
                            if (imgHelper.CheckInfoIcon(hpf))
                            {
                                string fileName = hpf.FileName;
                                newsProductThumb = new NewsProductThumb();
                                newsProductThumb.NProId = newsProduct.NProId;
                                newsProductThumb.NProThumbName = fileName;
                                string path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + hpf.FileName);
                                if (isMainThumb)
                                {
                                    //Up hình lên server
                                    imgHelper.uploadImage(path, hpf, 200, 200);
                                    //Thêm vào CSDL 
                                    newsProductThumb.NProThumbIsMain = true;
                                    isMainThumb = false;
                                    newsProThumbHelper.Add(newsProductThumb);
                                    newsProThumbHelper.Save();
                                    continue;
                                }
                                newsProductThumb.NProThumbIsMain = false;

                                //Upload hình lên server
                                imgHelper.uploadImage(path, hpf, 200, 200);
                                //Thêm vào CSDL
                                newsProThumbHelper.Add(newsProductThumb);
                                newsProThumbHelper.Save();
                            }
                        }
                    }
                    else
                    {
                        foreach (var issue in newsProduct.GetRuleViolations())
                        {
                            ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                        }
                        Init(uid);
                        return View("~/Views/Private/ProductCreate.aspx");
                    }
                }
                return RedirectToAction("Index", "Product", new { uid = (int)Session["MemId"] });
            }
            return HomePage();
        }


        public RedirectResult updateCate(FormCollection data)
        {
            string arr = "";
            for (int i = 0; i < data.Count; i++)
            {
                if (!data[i].ToLower().Equals("-1"))
                    arr += data[i] + ",";
            }
            Member currMem = new MemberHelper().getMember(int.Parse(Session["MemId"] + ""));
            currMem.MemCategoryList = arr;
            new MemberHelper().updateMemberCatList(currMem);
            return Redirect(Request.UrlReferrer.AbsoluteUri + "#");
        }

        public ActionResult List(int? uid, bool isEditMode,FormCollection data)
        {
            if (uid == null)
                return HomePage();
            if (Session["MemId"] != null)
                if (int.Parse(Session["MemId"] + "") != uid)
                    ViewData["isEditMode"] = "False";
                else
                    ViewData["isEditMode"] = "True";
            else
                ViewData["isEditMode"] = "False";
            if (LoadMember(uid.Value) == null)
            {
                Init(uid);
                CategoryHelper cateHelper = new CategoryHelper();
                if (isEditMode)
                {
                    ViewData["Mode"] = "Editing";
                    //Lấy tất cả các danh mục của các trang để hiện thị trong combobox
                    //dùng trong trường hợp chỉnh sửa vị trí của danh mục

                    //lưu thông tin cate

                    List<Category> list =cateHelper.getCates(0);
                    Category tmpCate = new Category();
                    tmpCate.CateId = -1;
                    tmpCate.CateCount = 0;
                    tmpCate.CateIcon = null;
                    tmpCate.CateName = "Không hiển thị";
                    tmpCate.PageId = null;
                    tmpCate.ParentCateId = null;
                    list.Insert(0, tmpCate);
                    ViewData["ListCates"] = new SelectList(list, "CateId", "CateName");
                }
                else
                {
                    ViewData["Mode"] = "Show";
                    //Kiem tra neu user nay chua luu danh sach cac danh muc thi
                    MemberHelper memHelper = new MemberHelper();
                    Member mem = memHelper.getMember(uid.Value);
                    List<Category> listCateId = null;
                    if (string.IsNullOrEmpty(mem.MemCategoryList))
                        //Load 12 category mac dinh
                        listCateId = cateHelper.getDefaultCategory(12);
                    else //User da luu danh sach cac danh muc thi load len va hien thi
                    {
                        string[] listId = mem.MemCategoryList.Split(',');
                        listCateId = new List<Category>();
                        foreach (string id in listId)
                        {
                            if (!string.IsNullOrEmpty(id))
                                listCateId.Add(cateHelper.getCate(int.Parse(id)));
                        }
                    }
                    //Luu lai cau hinh danh muc mac dinh (cac link dung de phan loai danh muc trong trang productlist.aspx)
                    string chainOfId = "";
                    foreach (var item in listCateId)
                    {
                        chainOfId += item.CateId + ",";
                    }
                    mem.MemCategoryList = chainOfId;
                    memHelper.Save();
                    ViewData["ListLinks"] = listCateId;
                    //
                }
                int pageNum;
                if (!int.TryParse(Request.QueryString["p"], out pageNum))
                    pageNum = 1;
                NewsProductHelper newsProductHelper = new NewsProductHelper(uid.Value);
                int cateId;
                if (Request.QueryString["cateId"] == null)//Truong hop load dau tien
                {
                    //Mac dinh hien thi danh muc dau tien trong CSDL du hien thi
                    ViewData["ListNewsProduct"] = newsProductHelper.AllProductByMemId(pageNum, Config.ITEMS_PER_PAGE);
                    ViewData["MemId"] = uid.Value;
                    return View("~/Views/Private/ProductList.aspx");
                }
                else
                {
                    cateId = int.Parse(Request.QueryString["cateId"]);
                }
                ViewData["CurrCateId"] = cateId;
                ViewData["ListNewsProduct"] = newsProductHelper.AllNewsProductApprovedByMemId(pageNum, Config.ITEMS_PER_PAGE, cateId);
                ViewData["MemId"] = uid.Value;

                return View("~/Views/Private/ProductList.aspx");
            }
            return HomePage();
        }

        public ActionResult ListToModify(int? uid)
        {
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                //Kiểm tra có phải là chủ nhân, nếu đúng thì cho sửa, không thì bắt login
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();
                Init(uid);
                ViewData["child_menu"] = "editing";
                int pageNum;
                if (int.TryParse(Request.QueryString["p"], out pageNum))
                {
                    NewsProductHelper newsProductHelper = new NewsProductHelper(uid.Value);
                    var newsProduct = newsProductHelper.getListProduct(pageNum);
                    ViewData["ListNewsProduct"] = newsProduct;
                    return View("~/Views/Private/ProductListToModify.aspx");
                }
                else
                {
                    pageNum = 1;
                    NewsProductHelper newsProductHelper = new NewsProductHelper(uid.Value);
                    var newsProduct = newsProductHelper.getListProduct(pageNum);
                    ViewData["ListNewsProduct"] = newsProduct;
                    return View("~/Views/Private/ProductListToModify.aspx");
                }
            }
            return HomePage();
        }

        [HttpGet]
        public ActionResult DeleteProduct(int? uid, int productId, int currPage)
        {
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null && (bool)ViewData["IsOwner"])
            {
                //Kiểm tra có phải là chủ nhân, nếu đúng thì cho sửa, không thì bắt login
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();
                Init(uid);
                NewsProductHelper productHelper = new NewsProductHelper();
                //Load và delete product
                NewsProduct product = productHelper.getNewsProductById(productId);
                if (product != null)
                {
                    productHelper.Delete(product);
                    productHelper.Save();
                }
                return RedirectToAction("ListToModify", "Product", new { uid = Session["MemId"], p = currPage });
            }
            return HomePage();
        }

        [HttpGet]
        public ActionResult LoadToEditProduct(int? uid, int productId)
        {
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                //Kiểm tra có phải là chủ nhân, nếu đúng thì cho sửa, không thì bắt login
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();
                Init(uid);
                ViewData["child_menu"] = "editing";
                NewsProductHelper productHelper = new NewsProductHelper();
                //Load và delete product
                NewsProduct product = productHelper.getNewsProductById(productId);
                if (product.RAttrId == null)  //Nếu sản phẩm đang chỉnh sửa là product
                    ViewData["NewsType"] = "Product";
                else
                    ViewData["NewsType"] = "RealEstate";
                ViewData["ProductToEdit"] = product;

                UtilityModel uModel = new UtilityModel();
                SelectList listProvinces = new SelectList(uModel.ListProvince(), "ProvId", "ProvName", product.Province.ProvId);
                ViewData["Provinces"] = listProvinces;

                CategoryHelper cateHelper = new CategoryHelper();
                //SelectList listCate = new SelectList(cateHelper.getAllParentCate(), "CateId", "CateName", product.ParentCateId);
                //ViewData["Categories"] = listCate;
                //ViewData["CateLevel1"] = product.ParentCateId;
                ViewData["CateLevel2"] = product.CateId;
                return View("~/Views/Private/EditProduct.aspx");
            }
            return HomePage();
        }

        [HttpPost]
        public ActionResult Controller(FormCollection data)
        {
            int? uid = null;
            if (Session["MemId"] != null)
                uid = (int)Session["MemId"];
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                //Kiểm tra có phải là chủ nhân, nếu đúng thì cho sửa, không thì bắt login
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();

                Init(uid);
                NewsProductHelper productHelper = new NewsProductHelper();
                String[] lstProductId = data.GetValues("checkbox");
                int p = data.Get("currPage") == null ? 1 : int.Parse(data.Get("currPage"));
                if (!this.IsLogin)
                    return HomePage();
                Init(uid);
                var result = LoadMember(uid.Value);
                //Click "xoa" button
                if (result == null && (bool)ViewData["IsOwner"]) //Load được Member và người này đủ quyền để chỉnh sửa dữ liệu
                {
                    if (data.Get("hidCmd").Equals("del"))
                    {
                        if (lstProductId != null)
                        {
                            foreach (string item in lstProductId)
                            {
                                NewsProduct product = productHelper.getNewsProductById(int.Parse(item));
                                productHelper.Delete(product);
                                productHelper.Save();
                            }
                        }
                    }
                    //Click "chuyen trang thai" button
                    if (data.Get("hidCmd").Equals("ChangeState"))
                    {
                        if (lstProductId != null)
                        {
                            foreach (string item in lstProductId)
                            {
                                NewsProduct product = productHelper.getNewsProductById(int.Parse(item));
                                if (product != null)
                                {
                                    if (product.NProState)
                                        product.NProState = false;
                                    else
                                        product.NProState = true;
                                    productHelper.Save();
                                }
                            }
                        }
                    }
                }
                return RedirectToAction("ListToModify", "Product", new { uid = Session["MemId"], p = p });
            }
            return HomePage();
        }

        public ActionResult ListRealEstate(int? uid)
        {
            if (uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                Init(uid);
                NewsProductHelper newsProductHelper = new NewsProductHelper();
                ViewData["ListRealEstate"] = newsProductHelper.AllRealEstateApprovedByMemId(uid.Value);
                ViewData["MemId"] = uid.Value;
                return View("~/Views/Home/RealEstate_List.aspx");
            }
            return HomePage();
        }

        [HttpGet]
        public ActionResult Details(int id, int? uid)
        {
            if (uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                Init(uid);
                NewsProductHelper newsProductHelper = new NewsProductHelper();
                ViewData["NewsProduct"] = newsProductHelper.getNewsProductById(id);
                return View("~/Views/Private/ProductDetail.aspx");
            }
            return HomePage();
        }

        [HttpGet]
        public ActionResult DeleteImage(int id, int productId)
        {
            int? uid = null;
            if (Session["MemId"] != null)
                uid = (int)Session["MemId"];
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();
                //Tìm đối tượng hình cần xóa
                NewsProductThumbHelper prodThumbHelper = new NewsProductThumbHelper();
                NewsProductThumb prodThumb = prodThumbHelper.getProductThumbById(id);
                prodThumbHelper.Delete(prodThumb);
                prodThumbHelper.Save();
                //Xóa hình trong thư mục
                string oldImg = prodThumb.NProThumbName;
                ImageHelper imgHelper = new ImageHelper();
                if (!String.IsNullOrEmpty(oldImg))
                {
                    //Xóa hình trong thư mục thumbnail và cả trong thư mục upload
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + oldImg));
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload"), oldImg));
                }
                return LoadToEditProduct(uid, productId);
            }
            return HomePage();
        }

        [HttpPost]
        public ActionResult ChangeImage(FormCollection data)
        {
            int? uid = null;
            if (Session["MemId"] != null)
                uid = (int)Session["MemId"];
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();
                int prodId = int.Parse(data.Get("prodId"));
                int thumbId = int.Parse(data.Get("thumbId"));
                string oldImageName = data.Get("oldImageName");
                HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;
                ImageHelper imgHelper = new ImageHelper();
                if (imgHelper.CheckInfoIcon(hpf))
                {
                    //Xóa hình cũ trước khi upload hình mới
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + oldImageName));
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload"), oldImageName));
                    string path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + hpf.FileName);
                    //Thay đổi trong CSDL và upload hình mới
                    string fileName = hpf.FileName;
                    NewsProductThumbHelper thumbHelper = new NewsProductThumbHelper();
                    NewsProductThumb newsProductThumb = thumbHelper.getProductThumbById(thumbId);
                    newsProductThumb.NProThumbName = fileName;
                    //Up hình lên server
                    UploadController upload = new UploadController();
                    imgHelper.uploadImage(path, hpf, 200, 200);
                    thumbHelper.Save();
                }
                return LoadToEditProduct(uid, prodId);
            }
            return HomePage();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult EditProduct(FormCollection data)
        {
            int? uid = null;
            if (Session["MemId"] != null)
                uid = (int)Session["MemId"];
            if (!this.IsLogin || uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null)
            {
                if (ViewData["IsOwner"] == null)
                    return HomePage();
                if ((bool)ViewData["IsOwner"] == false)
                    return HomePage();
                int newsProductId = int.Parse(data.Get("productId"));
                NewsProductHelper prodHelper = new NewsProductHelper();
                NewsProduct prodToEdit = prodHelper.getNewsProductById(newsProductId);
                //Các phần chung giữa sản phẩm và nhà đất
                prodToEdit.NProTitle = data.Get("txtTitle");
                prodToEdit.NProIntro = data.Get("txtIntro");
                prodToEdit.NProFrom = data.Get("txtFrom");
                prodToEdit.NProNeedType = data.Get("grpDemand");
                prodToEdit.NProContent = data.Get("txtDetailContent");
                prodToEdit.ProvId = int.Parse(data.Get("ddlProvince"));
                prodToEdit.NProPrice = decimal.Parse(data.Get("txtPrice"));
                //prodToEdit.ParentCateId = int.Parse(data.Get("ddlCateLevel1"));
                prodToEdit.CateId = int.Parse(data.Get("ddlCateLevel2"));
                prodToEdit.NProDate = DateTime.Now;
                prodToEdit.NProState = false;

                if (prodToEdit.RAttrId != null) // Chỉnh sửa phần nhà đất
                {
                    RealEStateAttributeHelper rAttHelper = new RealEStateAttributeHelper();
                    RealEstateAttribute attr = rAttHelper.getRealEstateAttributeById(prodToEdit.RAttrId.Value);

                    // Phần Tiện ích
                    attr.RAttrWaterSystem = data.Get("ckbWaterSystem") != null ? true : false;
                    attr.RAttrPrivateElecClock = data.Get("ckbPrivateElecClock") != null ? true : false;
                    attr.RAttrUsableArea = data.Get("txtUsableArea") != "" ? double.Parse(data.Get("txtUsableArea")) : 0;
                    attr.RAttrTotalArea = data.Get("txtTotalArea") != "" ? double.Parse(data.Get("txtTotalArea")) : 0;
                    attr.RAttrFloorCount = data.Get("txtFloorCount") != "" ? int.Parse(data.Get("txtFloorCount")) : 0;

                    //Phần Nội thất - Tiện nghi
                    attr.RAttrElevator = data.Get("ckbElevator") != null ? true : false;
                    attr.RAttrGarden = data.Get("cbkGarden") != null ? true : false;
                    attr.RAttrPhoneLine = data.Get("ckbPhoneLine") != null ? true : false;
                    attr.RAttrGarage = data.Get("ckbGarage") != null ? true : false;
                    attr.RAttrSecurity24 = data.Get("ckbSecurity24") != null ? true : false;
                    attr.RAttrAirCondition = data.Get("ckbAirCondition") != null ? true : false;
                    attr.RAttrSwimmingPool = data.Get("ckbSwimmingPool") != null ? true : false;
                    attr.RAttrLivingRoom = data.Get("ckbLivingRoom") != null ? true : false;
                    attr.RAttrCarParking = data.Get("ckbCarParking") != null ? true : false;
                    attr.RAttrTopFloor = data.Get("ckbTopFloor") != null ? true : false;
                    attr.RAttrKitchen = data.Get("ckbKitchen") != null ? true : false;

                    //Phần Văn hóa - Xã hội
                    attr.RAttrNearPark = data.Get("ckbNearPark") != null ? true : false;
                    attr.RAttrNearComCentral = data.Get("ckbNearComCentral") != null ? true : false;
                    attr.RAttrNearHighSchool = data.Get("ckbNearHighSchool") != null ? true : false;
                    attr.RAttrForBusiness = data.Get("ckbForBusiness") != null ? true : false;
                    attr.RAttrForEnterCenter = data.Get("ckbNearEnterCenter") != null ? true : false;
                    attr.RAttrNearColleage = data.Get("ckbNearColleage") != null ? true : false;
                    attr.RAttrNearMarket = data.Get("ckbNearMarket") != null ? true : false;
                    attr.RAttrNearPrimarySchool = data.Get("ckbNearPrimarySchool") != null ? true : false;
                    attr.RAttrNearKinderGarden = data.Get("ckbNearKinderGarden") != null ? true : false;
                    attr.RAttrNearHospital = data.Get("ckbNearHospital") != null ? true : false;
                    attr.RAttrNearSecondarySchool = data.Get("ckbNearSecondarySchool") != null ? true : false;
                    attr.RAttrHighIntelResident = data.Get("ckbHighIntelResident") != null ? true : false;

                    //Tình trạng - Pháp lý
                    switch (data.Get("Book"))
                    {
                        case "RedBook": attr.RAttrRedBook = true; break;
                        case "PinkBook": attr.RAttrPinkBook = true; break;
                        case "rbtHandWritingBook": attr.RAttrHandwrittingBook = true; break;
                    }

                    //Thêm attr vào CSDL
                    rAttHelper.Save();
                }

                if (prodToEdit.IsValid)
                {
                    prodHelper.Save();
                    return ListToModify(uid);
                }
                else
                {
                    foreach (var issue in prodToEdit.GetRuleViolations())
                    {
                        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                    }
                }
            }
            return HomePage();
        }

        //public ActionResult EditCategoryTable(int? uid, int currCateId)
        //{
        //    ViewData["Mode"] = "Editing";
        //    CategoryHelper cateHelper = new CategoryHelper();
        //    //Lấy tất cả các danh mục của các trang để hiện thị trong combobox
        //    //dùng trong trường hợp chỉnh sửa vị trí của danh mục
        //    ViewData["ListCates"] = new SelectList(cateHelper.getCates(null), "CateId", "CateName");
        //    return List(uid, currCateId,true);
        //}

        //[HttpPost]
        //public ActionResult RenderLink(FormCollection data, int cateId)
        //{
        //    if (Session["MemId"] == null && ViewData["IsOwner"] == null)
        //        return HomePage();
        //    int uid = (int)Session["MemId"];
        //    List<Category> listLink = new List<Category>();
        //    if (LoadMember(uid) == null && (bool)ViewData["IsOwner"] == true)
        //    {
        //        CategoryHelper cateHelper = new CategoryHelper();
        //        for (int i = 1; i <= 12; i++)
        //        {
        //            string idCate = data.Get("drop_"+ i);   
        //            listLink.Add(cateHelper.getCate(int.Parse(idCate)));    
        //            ViewData["ListLinks"] = listLink;
        //        }
        //        ViewData["Mode"] = "Show";
        //        return List(uid, cateId,listLink);
        //    }
        //    return HomePage();
        //}
    }
}
